<?php
namespace App\Service\OrderService\OrderInterfaceService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\PssModel\OrderRefund;
use App\Model\PssModel\OrderRefundLog;
use App\Service\PushService\BusinessPushService;
use App\Model\PssModel\OrderSupplier;
use App\Service\OrderService\OrderRefundService\OrderRefundMessage;
use App\Service\OrderService\OrderBdCrmTradeService;
use App\Model\PssModel\OrderRefundGoods;
use App\Service\AppService\PushOrderSettleMentService;
use App\Model\PssModel\OrderSettlementMiddle;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\CommodityModel\SupplierCompany;
use App\Model\CommodityModel\WarehouseInfo;
use App\Model\PssModel\OrderSupplierAmountExtra;

/**
 * 云仓同步BBC数据付款审核消息
 * 付款审核
 */
class OrderAfterSaleVerifyRefundAmount extends BaseService
{
    const amount_type_pass      = 1;
    const amount_type_reject    = 2;
    
    /**
     * 付款审核
     */
    public function index( array $param = [] )
    {
        $binfo  = $param['binfo'];
        $bid    = $binfo['bid'];
        
        //当前换货申请，仅支持自营BBC业务
        if( $binfo['is_support_aftersale_verify'] != 1 ) {
            return Normal::returnCode(Normal::FAIL,"当前付款申请，仅支持自营BBC业务");
        }
        
        $order = $param['requestData'];
        
        if( empty($order['refundID']) ) {
            return Normal::returnCode(Normal::FAIL,"售后订单refundID不能为空");
        }
        
        if( empty($order['refundAmountType']) ) {
            return Normal::returnCode(Normal::FAIL,"售后付款方式refundAmountType不能为空");
        }
        
        $refundID               = $order['refundID'];
        $refundAmountType       = $order['refundAmountType'];
        $orderRefund            = OrderRefund::instance()->info(['bid'=>$bid,'id'=>$refundID]);
        if( empty($orderRefund)) {
            return Normal::returnCode(Normal::FAIL,"售后申请订单记录不存在，请联系管理员进行核实处理");
        }

        $refundType = $orderRefund['refund_type'];
        $isRefundTypeRelationMoney = OrderRefundMessage::instance()->isNeedRefundMoney($refundType);
        if( !$isRefundTypeRelationMoney) {
            return Normal::returnCode(Normal::FAIL,"当前售后订单不涉及退款操作，请联系管理员进行核实处理");
        }
        if($refundType == OrderRefundMessage::refund_type_goodsandmoney && in_array($orderRefund['warehouse_change_status'], ['0', '2'])){
            return Normal::returnCode(Normal::FAIL,"退货退款类型必须先确认退货确认后才能退款");
        }
        if( empty($order['refundAmountStatus']) ) {
            return Normal::returnCode(Normal::FAIL,"售后退款金额refundAmountStatus不能为空");
        }
        
        if( empty($order['refundAmountAttaches']) ) {
            return Normal::returnCode(Normal::FAIL,"售后付款凭证refundAmountAttaches不能为空");
        }
        
        if( empty($order['sysUserID']) ) {
            return Normal::returnCode(Normal::FAIL,"操作人员sysUserID不能为空");
        }
        
        if( empty($order['sysUserName']) ) {
            return Normal::returnCode(Normal::FAIL,"操作人员sysUserName不能为空");
        }
        
        $refundAmountAttaches   = @json_decode($order['refundAmountAttaches'],true);
        if( empty($refundAmountAttaches)) {
            return Normal::returnCode(Normal::FAIL,"付款单审核付款凭证解析错误，请核对上传数据格式!");
        }
        
        if( !isset(OrderRefund::instance()->refund_amount_type[$refundAmountType]) ) {
            return Normal::returnCode(Normal::FAIL,"退款单审核付款方式枚举不正确");
        }
        
        if( $orderRefund['refund_amount_status'] == 1 ) {
            return Normal::returnCode(Normal::FAIL,"当前售后订单已审核退款成功，无须再次操作!");
        }

        if( $orderRefund['refund_amount_status'] == 2 ) {
            return Normal::returnCode(Normal::FAIL,"当前售后订单已被拒绝，请先核对售后订单之后，再次审核!");
        }
        
        //判断是否是云仓应该审核的退款单
        if( $orderRefund['refund_source'] == OrderRefundMessage::refund_source_channel ) {
            return Normal::returnCode(Normal::FAIL,"当前云仓不能审核BBC自己的退款单，请联系管理员进行核实处理");
        }
        
        $refund_status      = $orderRefund['refund_status'];
        $order_refund_id    = $orderRefund['id'];
        
        //原始订单信息
        $supplierOrder = OrderSupplier::instance()->info(['id'=>$orderRefund['sub_order_id']]);
        if( empty($supplierOrder)) {
            return Normal::returnCode(Normal::FAIL,"原始供应商订单数据不存在，请联系管理员进行核实处理");
        }
        if($supplierOrder['is_top_system'] == 0 &&  in_array($refund_status, ['2','5','6']) && $order['refundAmountStatus'] == self::amount_type_reject){
            return Normal::returnCode(Normal::FAIL,"当前数据上级云仓已审核通过 退款审核不能拒绝");
        }

        //2-同意退款，退款中 6-退货退款，待平台处理
        $_where_refund_status = ['2','5','6'];
        if( !in_array($refund_status,$_where_refund_status) && $supplierOrder['order_status'] == 2 ) {
            return Normal::returnCode(Normal::FAIL,"当前售后订单必须要满足【2-同意退款，退款中 6-退货退款，待平台处理】其中之一的状态，请联系管理员进行核实处理");
        }
        
        //未发货情况
        if( $supplierOrder['order_status'] == 1 ) {
            $_where_refund_status = ['1','2','5','6'];
        }
        
        //未发货情况
        if( $supplierOrder['order_status'] = 0 ) {
            return Normal::returnCode(Normal::FAIL,"当前售后订单必须要满足已支付，请联系管理员进行核实处理");
        }
        
        //获取供应商信息
        $companyInfo = SupplierCompany::instance()->getSupplierListById($supplierOrder['company_id']);
        if( empty($companyInfo) ) {
            return Normal::returnCode(Normal::FAIL,"此供应商信息异常，请联系管理员进行核实处理");
        }
        $warehouse  = WarehouseInfo::instance()->info(['SupplierId'=>$supplierOrder['company_id']]);
        if( empty($warehouse) ) {
            return Normal::returnCode(Normal::FAIL,"此仓库信息异常，请联系管理员进行核实处理");
        }
        $apiBody        = !empty($warehouse['JsonBody']) ? json_decode($warehouse['JsonBody'],true) : [];
        $supplierClass  = ucFirst( $companyInfo['OrderDockMode'] == 1 ? 'normal' : $companyInfo['company_code'] );
        $serviceClass   = "App\\Service\\OrderService\\OrderRouteService\\{$supplierClass}";
        if( !class_exists($serviceClass) ) {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} not existed");
        }
        
        $requestMethod = 'orderAfterSale';
        if( !method_exists($serviceClass,$requestMethod) ) {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} {$requestMethod} methods not existed");
        }
        
        //付款方式
        $refundAmountAttaches       = json_encode($refundAmountAttaches,JSON_UNESCAPED_UNICODE || JSON_UNESCAPED_SLASHES);
        $refund_amount_type_name    = OrderRefund::instance()->refund_amount_type[$refundAmountType];
        $sysUserID                  = $order['sysUserID'];
        $sysUserName                = $order['sysUserName'];
        $refundAmountStatus         = $order['refundAmountStatus'];
        
        //判断CRM是否上传过钱买分数据
        $refund_bd_crm_create       = !empty($orderRefund['refund_bd_crm_create']) ? @json_decode($orderRefund['refund_bd_crm_create'],true) : [];
        if( !empty($refund_bd_crm_create) && !empty($refund_bd_crm_create['isNeedBuyCent']) && $refundAmountStatus == self::amount_type_reject ) {
            return Normal::returnCode(Normal::FAIL,"钱买分抵扣已上传，不能次发起拒绝操作!");
        }
        
        //原始订单商品
        $orderGoods = OrderSupplierGoods::instance()->where('order_id',$supplierOrder['id'])->get()->toArray();
        $param = [
            'supplierOrder' => $supplierOrder,
            'orderGoods'    => $orderGoods,
            'order'         => $order,
            'binfo'         => $binfo,
            'apiBody'       => $apiBody
        ];
        
        //是否需要恢复结算数据
        $isNeedRecoverySettlement = ($supplierOrder['is_channel_settlement'] == 1 || $supplierOrder['is_supplier_settlement'] == 1 ) ? 1 : 0 ;
        
        //是否全部售后订单功能,如果是全部商品整单售后的情况下，才要通知供应商进行取消，否则走人工
        $isAllRefund        = OrderRefundMessage::instance()->isOrderGoodsAllRefund($order_refund_id,$orderGoods);
        
        //退款审核是否涉及到钱
        $isNeedRefundMoney  = OrderRefundMessage::instance()->isNeedRefundMoney($refundType);
        
        //查询是否预售订单
        $isPreSellOrder     = OrderPreSellService::instance()->isPreSellOrder($supplierOrder);
        
        //获取售后商品
        $orderRefundGoods = OrderRefundGoods::instance()->getRefundGoods($order_refund_id);
        if( empty($orderRefundGoods) ) {
            return Normal::returnCode(Normal::FAIL,"售后商品异常，请联系管理员进行处理!");
        }
        
        $refundGoods = [];
        foreach ($orderRefundGoods as $item) 
        {
            $refundGoods[] = [
                'goodsSku'                      => (string)$item['skucode'],
                'goodsSpecNum'                  => (string)$item['spec_num'],
                'goodsNum'                      => (string)$item['buy_num'],
                'goodsRefundNum'                => (string)$item['refund_num'],
                'goodsPrice'                    => (string)$item['price'],
                'goodsMoney'                    => (string)$item['refund_goods_money'],
                'goodsDeliveryMoney'            => (string)$item['refund_delivery_money'],
                'discountMoney'                 => (string)$item['refund_discount_money'],
                'discountPointsMoney'           => (string)$item['refund_discount_points_money'],
                'discountRedEnvelopeMoney'      => (string)$item['refund_discount_envelope_money'],
                'discountActivityMoney'         => (string)$item['refund_discount_activity_money'],
                'discountCouponMoney'           => (string)$item['refund_discount_coupon_money'],
                'discountPaywayMoney'           => (string)$item['refund_discount_payway_money'],
                'discountPrecardMoney'          => (string)$item['refund_discount_precard_money'],
                'discountDepositGoodsMoney'     => (string)$item['refund_discount_deposit_goods_money'],
                'discountDepositDeliveryMoney'  => (string)$item['refund_discount_deposit_delivery_money'],
                'discountPoints'                => (string)$item['refund_discount_points'],
            ];
        }
        
        //系统时间
        $refund_amount_time = getSystemDate();
        
        //是否只支付了定金
        $order_supplier_id  = $supplierOrder['id'];
        $isDepositMoneyOnly = OrderPreSellService::instance()->isDepositMoneyOnly($order_supplier_id);
        
        
        //上传CRM交易,退款单审核通过的时候
        $refund_buy_points_money = '0.00';
        $bd_crm_refund_money = [
            'deposit_refund_money' => '0.00',
            'final_refund_money' => '0.00',
            'deposit_money' => '0.00',
            'final_money' => '0.00'
        ];
        // if($binfo['is_support_crm_upload'] == 1){
        if( $refundAmountStatus == self::amount_type_pass && !$isDepositMoneyOnly )
        {
            $result = $this->uploadOrderCrmAfterSale($binfo, $orderRefund, $orderRefundGoods, $supplierOrder, $order);
            if( $result['code'] != Normal::SUC ) {
                return $result;
            }
            $refund_buy_points_money = $result['data']['refund_buy_points_money'];
            $bd_crm_refund_money = $result['data']['bd_crm_refund_money'];
        }
        else
        {
            if($binfo['is_support_crm_upload'] == 1){
                //拒绝的时候，判断CRM是否已经上传过，如果上传过，不允许拒绝
                $refund_bd_crm_contents = $orderRefund['refund_bd_crm_contents'];
                $refund_bd_crm_contents_arr = !empty($refund_bd_crm_contents) ? json_decode($refund_bd_crm_contents,true) : [];
                if( !empty($refund_bd_crm_contents_arr['serverBillIdPreConfirmPay']) && $refund_bd_crm_contents_arr['serverBillIdPreConfirmPay'] == true ) {
                    return Normal::returnCode(Normal::FAIL,"售后退款审核订单数据已上传CRM,不能再进行拒绝操作，请直接审核通过!");
                }
            }
        }
        // }
        //是否预售订单非全款模式
        $_extra_money = OrderSupplierAmountExtra::instance()->info(['order_id'=>$order_supplier_id]);
        $isPreSellNoneAllPayMoneyOrder = OrderPreSellService::instance()->isPreSellNoneAllPayMoneyOrder($supplierOrder, $_extra_money);
        
        //钱买分金额直接读取售后表的金额
        $refund_buy_points_money = $orderRefund['refund_buy_points_money'];
        
        try
        {
            OrderRefund::instance()->startTrans();
            
            //付款单审核修改
            $updateExpressArr = [
                'md'                            => time(),
                'refund_amount_type'            => $refundAmountType,
                'refund_amount_attaches'        => $refundAmountAttaches,
                'refund_amount_status'          => $refundAmountStatus,
                'refund_amount_time'            => $refund_amount_time,
                'refund_order_verify_user_id'   => $sysUserID,
                'refund_order_verify_user_name' => $sysUserName
            ];
            
            if( $refundAmountStatus == self::amount_type_pass )
            {
                $refundAmountStatusName = "售后付款单审核通过";
                //计算实际退款金额
                $refund_service_fee_money = $orderRefund['refund_service_fee_money'];
                $refund_money             = $orderRefund['refund_money'];
                $refundRealyMoney         = bcsub((string)$refund_money,(string)$refund_service_fee_money,2);
                $refundRealyMoney         = bcsub((string)$refundRealyMoney,(string)$refund_buy_points_money,2);
                $updateExpressArr['refund_realy_money'] = $refundRealyMoney;
                $updateExpressArr['refund_buy_points_money'] = $refund_buy_points_money;
                
                //审核通过,更新已经处理退款的金额,预售订单非全款模式
                if( $isPreSellNoneAllPayMoneyOrder ) 
                {
                    $_update_extra_amount = [];
                    if( !empty($bd_crm_refund_money['deposit_refund_money']) ) {
                        $_update_extra_amount['deposit_refund_money'] = $bd_crm_refund_money['deposit_refund_money'];
                    }
                    
                    if( !empty($bd_crm_refund_money['final_refund_money']) ) {
                        $_update_extra_amount['final_refund_money'] = $bd_crm_refund_money['final_refund_money'];
                    }
                    if(!empty($_update_extra_amount)){
                       OrderSupplierAmountExtra::instance()->where('order_id',$order_supplier_id)->update($_update_extra_amount);
                    }
                }
            }
            else
            {
                $refundAmountStatusName = "售后付款单审核拒绝";
                $updateExpressArr['refund_status'] = 1;
                $refund_bd_crm_contents = json_decode($orderRefund['refund_bd_crm_contents'],true);
                if ( !empty($refund_bd_crm_contents['bd_crm_create']) ) {
                    unset($refund_bd_crm_contents['bd_crm_create']);
                }
                if ( !empty($refund_bd_crm_contents['serverBillIdPrePay']) ) {
                    unset($refund_bd_crm_contents['serverBillIdPrePay']);
                }
                if ( !empty($refund_bd_crm_contents['serverBillIdPreConfirmPay']) ) {
                    unset($refund_bd_crm_contents['serverBillIdPreConfirmPay']);
                }
                $updateExpressArr['refund_bd_crm_contents'] = json_encode($refund_bd_crm_contents,JSON_UNESCAPED_UNICODE);
                
                //退款单审核拒绝
                OrderSupplier::instance()->where('id',$order_supplier_id)->update([
                    'after_channel_notify_status'   => 0,
                    'after_channel_notify_remark'   => '退款单审核拒绝'
                ]);
            }
            
            $result = OrderRefund::instance()
            ->where('id',$order_refund_id)
            ->whereIn('refund_status',$_where_refund_status)
            ->whereIn('refund_amount_status',['0','2'])
            ->update($updateExpressArr);
            if( !$result ) {
                OrderRefund::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,"付款单审核处理失败，请联系管理员进行核实处理");
            }
                        
            //写入订单日志
            OrderRefundLog::instance()->addLog($order_refund_id,"付款单审核-[{$refund_amount_type_name}{$refundAmountStatusName}]",$sysUserID,$sysUserName);
                
            //退款单审核拒绝，不需要通知下游
            if( $refundAmountStatus == self::amount_type_reject ) {
                OrderRefund::instance()->commit();
                return Normal::returnCode(Normal::SUC,"操作成功");
            }
            
            //财务审核退款之后需要完成的操作：加入售后结算、推送CRM售后交易、推送供应商取消订单、推送下游审核退款操作、恢复云仓库存            
            //加入结算
            //开始对上游进行售后(云仓商城的订单售后需要审核),或者是下游直接审核通过
            //产生了订单货款结算记录，才进行恢复结算数据操作
            //一定要是通知下游渠道body 里面 $refundAmountStatus =1 才写入售后结算数据
            //部分售后里面换货申请，不纳入结算售后功能
            //只支付了定金，不参与售后结算
            if( $isNeedRefundMoney && $isNeedRecoverySettlement == 1 && !$isDepositMoneyOnly ) {
                OrderSettlementMiddle::instance()->addLog($binfo['bid'],$order_refund_id,PushOrderSettleMentService::SETTLEMENT_MODE_AFTER_SALE);
            }
            
            //推送供应商进行售后
            //要判断是否整单售后了之后，才通知供应商
            $order_push_status = $supplierOrder['order_push_status'];
            $after_supplier_notify_status = $supplierOrder['after_supplier_notify_status'];
            $order_supplier_id = $supplierOrder['id'];
            $result_code = 1;
            $result_msg = '处理成功';
            if(!isset($companyInfo['JsonBody']['is_new_mode'])){
                if($isAllRefund == 1 && $order_push_status == 1 && $refundAmountStatus == self::amount_type_pass && $after_supplier_notify_status != 1 )
                {
                    $param['order']['exceptReason'] = $param['orderSupplier']['after_sale_remark'] ?? '客户审核售后';
                    $result_supplier = $serviceClass::instance()->$requestMethod($param);
                    $result_code = $result_supplier['code'] == Normal::SUC ? 1 : 2;
                    $result_msg  = !empty($result_supplier['msg']) ? $result_supplier['msg'] : '请求失败';
                    //如果通知供应商失败了，这个时候要将云仓里面订单状态修改为审核拒绝
                    if( $result_code == 2 )
                    {
                        $update_after_sale_change = [
                            'orderId'               => $order_supplier_id,
                            'afterVerifyStatus'     => OrderAfterSaleVerify::AFTER_SALE_VERIFY_REJECT,
                            'afterVerifyRemark'     => $result_msg,
                            'afterVerifyAll'        => $isAllRefund
                        ];
                        $res = OrderAfterSaleVerify::instance()->orderAfterSaleVerifyChange($update_after_sale_change);
                        if( $res['code'] != Normal::SUC ) {
                            OrderRefund::instance()->rollback();
                            return $res;
                        }

                        //如果为第三方渠道则直接返回云仓错误信息,让操作员自行处理
                        OrderRefund::instance()->rollback();
                        return Normal::returnCode(Normal::FAIL,"当前渠道商订单推送供应商订单取消作废失败『{$result_msg}』，如需要继续审核，请先解绑供应商订单绑定关系之后，再发起售后审核退款操作!");
                    }

                    OrderSupplier::instance()->where('id',$order_supplier_id)->update([
                        'after_supplier_notify_status'  => $result_code,
                        'after_supplier_notify_remark'  => $result_msg
                    ]);
                }
            }

            
            //退回的定金和尾款
            $refundDepositMoney = !empty($bd_crm_refund_money['deposit_money']) ? $bd_crm_refund_money['deposit_money'] : '0.00';
            $refundFinalMoney   = !empty($bd_crm_refund_money['final_money'])   ? $bd_crm_refund_money['final_money']   : '0.00';
            
            //如果只支付了定金金额退，实际退款金额等于定金退款金额
            if( $isPreSellOrder && $isDepositMoneyOnly ) {
                $refundDepositMoney = $refundRealyMoney;
            }
            
            //推送下游售后退款成消息
            $body = [
                'orderSn'                       => (string)$supplierOrder['order_sn'],
                'orderNo'                       => (string)$supplierOrder['supplier_csn'],
                'refundID'                      => (string)$order_refund_id,
                'refundAmountType'              => (string)$refundAmountType,
                'refundAmountAttaches'          => (string)$refundAmountAttaches,
                'refundAmountTime'              => (string)$refund_amount_time,
                'refundAmountStatus'            => (string)$result_code,
                'refundAmountRemark'            => $result_code == 1 ? "审核退款通过通知" : "审核退款通过失败【{$result_msg}】",
                'refundType'                    => (string)$orderRefund['refund_type'],
                'refundApplyMoney'              => (string)$orderRefund['refund_apply_money'],
                'refundServiceFeeMoney'         => (string)$refund_service_fee_money,
                'refundRealyMoney'              => (string)$refundRealyMoney,
                'refundMoney'                   => (string)$refund_money,
                'refundBuyPointsMoney'          => (string)$refund_buy_points_money,
                'deliveryMoney'                 => (string)$orderRefund['refund_delivery_money'],
                'discountMoney'                 => (string)$orderRefund['refund_goods_money'],
                'goodsMoney'                    => (string)$orderRefund['refund_discount_money'],
                'discountPointsMoney'           => (string)$orderRefund['refund_points_money'],
                'discountRedEnvelopeMoney'      => (string)$orderRefund['refund_envelope_money'],
                'discountActivityMoney'         => (string)$orderRefund['refund_activity_money'],
                'discountCouponMoney'           => (string)$orderRefund['refund_coupon_money'],
                'discountPaywayMoney'           => (string)$orderRefund['refund_payway_money'],
                'discountPrecardMoney'          => (string)$orderRefund['refund_precard_money'],
                'discountPoints'                => (string)$orderRefund['refund_points_give'],
                'discountDepositGoodsMoney'     => (string)$orderRefund['refund_deposit_goods_money'],
                'discountDepositDeliveryMoney'  => (string)$orderRefund['refund_deposit_delivery_money'],
                'refundDepositMoney'            => (string)$refundDepositMoney,
                'refundFinalMoney'              => (string)$refundFinalMoney,
                'refundGoods'                   => $refundGoods
            ];
                        
            /*******************************同步渠道商订单功能*****************************/
            $channelPushFlag = false;
            //发起推送渠道商接口数据---审核退款操作
            if( $binfo['is_support_aftersale_verify'] == 1 && $supplierOrder['after_channel_notify_status'] != 3 && in_array($supplierOrder['order_type'],OrderAfterSaleVerify::instance()->channel_order_types) )
            {
                //此接口需要保证幂等
                $result_channel = BusinessPushService::instance()->pushMessage('OrderAfterSaleVerifyRefundAmount',$binfo,$body);
                
                //方便调试
                if( $result_channel['code'] != Normal::SUC ) 
                {
                    OrderRefund::instance()->rollback();
                    OrderSupplier::instance()->where('id',$order_supplier_id)->update([
                        'after_channel_notify_status'  => 4,
                        'after_channel_notify_remark'  => $result_msg
                    ]);
                    return Normal::returnCode(Normal::FAIL,"渠道商接收售后审核结果失败『{$result_msg}』");
                }
                
                OrderSupplier::instance()->where('id',$order_supplier_id)->update([
                    'after_channel_notify_status'  => 3,
                    'after_channel_notify_remark'  => $result_msg
                ]);
                $channelPushFlag = true;
            }
            //下游退款成功
            OrderRefund::instance()->commit();

            //如果是 不退货仅退款 和 退货退款 类型时 审核通过并且推送BBC通知成功的情况下 售后状态就 变为售后成功
            if( $refundAmountStatus == self::amount_type_pass && $channelPushFlag === true){
                $updateExpressArr2 = [];
                if($refundType == OrderRefundMessage::refund_type_refundnotgoodsbutmoney){
                    $updateExpressArr2['refund_status'] = OrderRefundMessage::refund_status_after_sale_success;
                }
                if($refundType == OrderRefundMessage::refund_type_goodsandmoney && $orderRefund['warehouse_change_status'] == 1){
                    $updateExpressArr2['refund_status'] = OrderRefundMessage::refund_status_after_sale_success;
                }
                if($updateExpressArr2){
                    OrderRefund::instance()->where('id',$order_refund_id)->update($updateExpressArr2);
                    OrderRefundLog::instance()->addLog($order_refund_id,"付款单审核-[{$refund_amount_type_name}退款成功且售后成功]",$sysUserID,$sysUserName);
                }
            }
            
            //恢复库存
            $this->recoverGoodsStock($orderGoods, $refundGoods,$binfo);
            return Normal::returnCode(Normal::SUC,"付款单审核处理完成");
        } 
        catch ( \Throwable $th)
        {
            OrderRefund::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,"付款单审核处理失败:{$th->getMessage()}，请联系管理员进行核实处理");
        }
    }
    
    /**
     * 上传钱买分售后交易凭证
     * @param array $binfo
     * @param array $orderRefund
     * @param array $orderRefundGoods
     * @param array $supplierOrder
     * @param array $order
     */
    public function uploadOrderCrmAfterSale(array $binfo,array $orderRefund,array $orderRefundGoods,array $supplierOrder,array $order)
    {
        $order_refund_id        = $orderRefund['id'];
        $order['refundType']    = $orderRefund['refund_type'];
        $is_support_crm_upload  = $binfo['is_support_crm_upload'];
        if( $is_support_crm_upload == 1 ) 
        {
            if( empty($orderRefund['refund_bd_crm_create']) ) {
                return Normal::returnCode(Normal::FAIL,"售后申请crm交易报文refund_bd_crm_create查询失败，请联系相关退款单管理人员去核销处理!");
            }
            if( empty($orderRefund['refund_bd_crm_contents']) ) {
                return Normal::returnCode(Normal::FAIL,"售后申请crm交易报文refund_bd_crm_contents查询失败，请联系相关退款单管理人员去核销处理!");
            }
            $refund_bd_crm_create   = @json_decode($orderRefund['refund_bd_crm_create'],true);
            $refund_bd_crm_contents = @json_decode($orderRefund['refund_bd_crm_contents'],true);
            if( empty($refund_bd_crm_contents) ) {
                return Normal::returnCode(Normal::FAIL,"售后crm交易查询解析失败，请联系相关退款单管理人员去核销处理!");
            }
            //组装会员ID
            $order['refund_extra_value']['vipId'] = $refund_bd_crm_create['requestData']['vipId'];
        }
        
        //售后交易上传
        $refund_buy_points_money = '0.00';
        if( !isset($refund_bd_crm_contents['refund_verify_create']) || empty($refund_bd_crm_contents['refund_verify_create']) )
        {
            $result_create = OrderBdCrmTradeService::instance()->uploadBdCrmOrderAfterSale($binfo, $orderRefund, $orderRefundGoods,$supplierOrder, $order);
            if( $result_create['code'] != Normal::SUC ) {
                return $result_create;
            }
        
            $refund_bd_crm_contents = $result_create['data'];
            if( !empty($refund_bd_crm_contents['needBuyCentMsg']) ) {
                return Normal::returnCode(Normal::FAIL,"售后crm交易查询解析失败【{$refund_bd_crm_contents['needBuyCentMsg']}，请联系相关退款单管理人员去核销处理】");
            }
            
            $refund_bd_crm_contents['refund_verify_create'] = true;
            OrderRefund::instance()->where('id',$order_refund_id)->update([
                'refund_bd_crm_contents'    => json_encode($refund_bd_crm_contents,JSON_UNESCAPED_UNICODE)
            ]);
        
            $refund_buy_points_money = (string)$refund_bd_crm_contents['needBuyCentMoney'];
            $orderRefund['refund_bd_crm_contents'] = json_encode($refund_bd_crm_contents,JSON_UNESCAPED_UNICODE);
        }
        
        $bd_crm_refund_money = $refund_bd_crm_contents['bd_crm_refund_money'];
        $result_pay = OrderBdCrmTradeService::instance()->uploadBdCrmOrderAfterPrepare($binfo, $orderRefund, $supplierOrder,$bd_crm_refund_money);
        if( $result_pay['code'] != Normal::SUC ) {
            return $result_pay;
        }

        $result_pay['data']['refund_buy_points_money'] = $refund_buy_points_money;
        $result_pay['data']['bd_crm_refund_money'] = $bd_crm_refund_money;
        return $result_pay;
    }
    
    /**
     * 恢复库存
     * @param array $orderGoods
     * @param array $refundGoods
     * @param array $binfo
     */
    public function recoverGoodsStock(array $orderGoods,array $refundGoods,array $binfo)
    {
        $refundGoodsMap = [];
        foreach ($orderGoods as $item) {
            $refundGoodsMap[$item['skucode']][$item['spec_num']] = $item;
            unset($item);
        }
        
        $recoverGoods = [];
        foreach ($refundGoods as $goods) 
        {
            $_origin_goods_info = $refundGoodsMap[$goods['goodsSku']][$goods['goodsSpecNum']];
            if( $_origin_goods_info['stock_id'] > 0 ) 
            {
                $recoverGoods[] = [
                    'goods_id'          => $_origin_goods_info['goods_id'],
                    'store_id'          => $_origin_goods_info['store_id'],
                    'stock_id'          => $_origin_goods_info['stock_id'],
                    'goods_name'        => $_origin_goods_info['goods_name'],
                    'quantity'          => $goods['goodsRefundNum'],
                    'spec_num'          => $_origin_goods_info['spec_num'],
                    'is_deduct_stock'   => $_origin_goods_info['is_deduct_stock']
                ];
            }
        }
        
        //恢复库存
        return OrderCancel::instance()->recoverGoodsStock([
            'orderGoods'    => $recoverGoods,
            'binfo'         => $binfo
        ]);
    }
}